package com.engine.update.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.interceptor.JdbcCommandContext;
import com.engine.core.interceptor.ResponseCommand;
import com.engine.core.util.QueryUtil;
import com.engine.core.util.Response;
import com.engine.system.User;

import java.util.Map;

public class SaveOrUpdateCommad extends ResponseCommand {
    public SaveOrUpdateCommad(User user, Map<String, Object> params) {
        super(user, params);
    }

    @Override
    public Response execute(JdbcCommandContext commandContext) throws Exception {
        Response response=Response.static_success("执行成功!");

        UpdateMultiCommand updateMultiCommand=new UpdateMultiCommand(user,params);
        Response updateRes= updateMultiCommand.execute(commandContext);

        JSONObject paramRoot=JSONObject.parseObject((String)params.get(QueryUtil.QUERY_CONTENT));
        String datas=paramRoot.getString(QueryUtil.UPDATA_DATA);
        JSONArray newDatas=new JSONArray();
        if(updateRes.isSuccess()){
            int results[]=(int[])updateRes.get("rows");
            if(results.length>1){
                JSONArray dataJson=JSON.parseArray(datas);
                for (int i = 0; i < results.length; i++) {
                    int result = results[i];
                    if(result==0){
                        JSONObject jo=dataJson.getJSONObject(i);
                        newDatas.add(jo);
                    }
                }
            }else{
                if(JSON.isValidArray(datas)){
                    newDatas.addAll(JSON.parseArray(datas));
                }else{
                    newDatas.add(JSON.parseObject(datas));
                }
            }
            if(newDatas.size()>0){
                paramRoot.put(QueryUtil.UPDATA_DATA,newDatas);
                params.put(QueryUtil.QUERY_CONTENT,paramRoot.toJSONString());
                SaveMultiCommand saveMultiCommand = new SaveMultiCommand(user,params);
                Response saveRes= saveMultiCommand.execute(commandContext);
                response.setMapValues(saveRes.getMapValues());
            }
        }
        return response;
    }
}
